/**
 * 当前的 “注册” 等操作，是基于 “本地存储” 完成的
 **/
(function (owner) {
    /**
     * 用户登录
     **/
    owner.login = function (loginInfo, callback) {
        callback = callback || $.noop;
        loginInfo = loginInfo || {};
        loginInfo.account = loginInfo.userno || '';
        loginInfo.password = loginInfo.password || '';
        if (loginInfo.account.length < 1) {
            return callback('账号最短为 1 个字符');
        }
        if (loginInfo.password.length < 1) {
            return callback('密码最短为 1 个字符');
        }
        var data = {
            USERNO: loginInfo.account,
            PASSWORD: loginInfo.password,
            APPNO: loginInfo.appno
        }
        owner.callAjaxPost("../../../api/LoginController/login", data, function (result) {
            if (result.success) {
                localStorage.setItem('$AdminUserInfo', JSON.stringify(result.data));
                return owner.createState(loginInfo.account, loginInfo.password, callback);
            } else {
                console.error("登录时发生错误：" + result);
                return callback(result.message);
            }
        });
    };

    //用户退出
    owner.exitApp = function () {
        var settings = owner.getSettings();
        var state = owner.getState();
        settings.isLogin = false; //将登陆状态设置为flase
        state.password = ""; //清空密码后需要用户重新登陆
        owner.setState(state);
        owner.setSettings(settings);
    }
    /* 创建适应多浏览器的XMLHttpRequest */
    function createXHR() {
        var xhr;
        if (window.XMLHttpRequest) {
            //针对以下浏览器：Firefox ,Mozillar ,Opera ,Safari ,IE7 ,IE8
            xhr = new XMLHttpRequest();
            //针对某些版本的Mozillar浏览器的BUG进行修正的
            if (xhr.overrideMimeType)
                xhr.overrideMimeType("text/html");
        }
        else if (window.ActiveXObject) {
            //针对IE的各种版本
            //将以下各种可用于创建XMLHttpRequest对象的控件名放在数组里面
            var versions = new Array();
            versions.push('Microsoft.XMLHTTP');
            versions.push('MSXML.XMLHTTP');
            versions.push('Microsoft.XMLHTTP');
            versions.push('Msxml2.XMLHTTP.7.0');
            versions.push('Msxml2.XMLHTTP.6.0');
            versions.push('Msxml2.XMLHTTP.5.0');
            versions.push('Msxml2.XMLHTTP.4.0');
            versions.push('MSXML2.XMLHTTP.3.0');
            versions.push('MSXML2.XMLHTTP');
            //尝试创建XMLHttpRequest对象
            for (var i = 0; i < versions.length; i++) {
                try {
                    //如果尝试创建成功的话，则终止循环
                    //如果创建失败的话，则抛出异常，继续循环，继续尝试创建
                    xhr = new ActiveXObject(versions[i]);
                    i = versions.length;
                }
                catch (e) {
                }
            }
        }
        //判断XMLHttpRequest对象是否创建成功
        if (xhr) {
            //返回XMLHttpRequest对象
            return xhr;
        }
        else {
            alert('XMLHttpRequest对象创建失败');
            return undefined;
        }
    };
    /* 异步调用服务器端方法 */
    owner.callAjaxPost = function (url, params, callback, scope,bLoading) {
        callback = callback || $.noop;
        url = url || "";
        if (url !== '')
            url = url + "?_dc=" + Math.random();
        params = params || {};

        var load ;
        if(bLoading == true){
            load = new loading();
            load.show();
        }

        /* 处理返回结果 */
        function dealwithResult(scope, result) {
            if (result) {
                if (callback) {
                    if (scope)
                        callback.call(scope, result);
                    else
                        callback.call(undefined, result);
                }
                else {
                    if (result.message !== '')
                        layer.alert(result.message);
                    else if (result.success !== true)
                        layer.alert("请求失败！",{icon:5});
                }
            }
        }

        $.ajax({
            url: url,
            data: JSON.stringify(params),
            dataType: 'json', //服务器返回json格式数据
            type: 'post', //HTTP请求类型
            contentType: "application/json",
            timeout: 15000, //超时时间设置为10秒；
            headers: {'Content-type': 'application/json;charset=UTF-8'},
            success: function (result) {
                if(bLoading == true){
                    load.close();
                }
                dealwithResult(scope, result);
            },
            error: function (xhr, type, errorThrown) {
                layer.alert("无法连接到服务器！",{icon:5});
                if(bLoading == true){
                    load.close();
                }
            }
        });
    }
    /* 同步调用服务器端方法上传文件 */
    owner.callAjaxPost4UpLoad = function (url, params, callback, scope) {
        callback = callback || $.noop;
        url = url || "";
        if (url !== '')
            url = url + "?_dc=" + Math.random();
        if (params === null || params === undefined || JSON.stringify(params) === '{}') {
            layer.alert("上传内容不能为空！",{icon:5});
            //alert("上传内容不能为空!");
            return;
        }
        var hasFiles = false;
        for (var param in params) {
            if (params[param] && !isNaN(params[param].size))
                hasFiles = true;
        }
        if (hasFiles === false) {
            layer.alert("上传内容不能为空！",{icon:5});
            //alert("上传内容不能为空!");
            return;
        }
        var formData = new FormData();
        for (var param in params)
            formData.append(param, params[param]);

        /* 处理返回结果 */
        function dealwithResult(scope, result) {
            if (result) {
                if (callback) {
                    if (scope)
                        callback.call(scope, result);
                    else
                        callback.call(undefined, result);
                }
                else {
                    if (result.message !== '')
                        layer.alert(result.message);
                    else if (result.success !== true)
                        layer.alert("请求失败",{icon:5});
                }
            }
        }

        /* IE使用 */
        if (!!window.ActiveXObject || "ActiveXObject" in window) {
            var xmlReq = createXHR();
            if (xmlReq) {
                if (scope)
                    xmlReq.scope = scope;
                xmlReq.onreadystatechange = function () {
                    if (xmlReq.readyState == 4 && xmlReq.status == 200) {
                        try {
                            var result = eval('(' + xmlReq.responseText + ')');
                            dealwithResult(xmlReq.scope, result);
                        }
                        catch (e) {
                            layer.alert("错误提示"+e.message,{icon:5});
                        }
                    }
                };
                xmlReq.open("POST", url, true);
                xmlReq.timeout = 15000;
                xmlReq.send(formData);
            }
        }
        else {
            $.ajax({
                url: url,
                type: 'POST',
                data: formData,
                async: false,
                cache: false,
                contentType: false,
                processData: false,
                success: function (result) {
                    dealwithResult(scope, result);
                },
                error: function (xhr, type, errorThrown) {
                    layer.alert("无法连接到服务器",{icon:5});
                }
            });
        }
    };
    /* 同步调用服务器端方法 */
    owner.callAjaxPostSync = function (url, params) {
        var obj;
        url = url || "";
        if (url !== '')
            url = url + "?_dc=" + Math.random();
        params = params || {};

        $.ajax({
            url: url,
            data: JSON.stringify(params),
            dataType: 'json', //服务器返回json格式数据
            type: 'post', //HTTP请求类型
            contentType: "application/json",
            async: false,
            timeout: 15000, //超时时间设置为10秒；
            headers: {'Content-type': 'application/json;charset=UTF-8'},
            success: function (result) {
                obj = result;
            },
            error: function (xhr, type, errorThrown) {
                layer.alert("无法连接到服务器！",{icon:5});
            }
        });
        return obj;
    };

    owner.createState = function (name, pwd, callback) {
        var state = owner.getState();
        state.account = name;
        state.password = pwd;
        state.token = "token123456789";
        owner.setState(state);
        return callback();
    };
    /*
     * 是否可以申报
     * @parma className:类名‘/Manual’
     */
    owner.GetCanbeSend = function (className, id, callback) {
        owner.callAjaxPost(owner.getHTIP() + className + "/GetCanbeSend", {id: id}, function (result) {
            if (result.success) {
                callback(result.data);
            } else {
                callback(false);
            }
        })
    }
    /**
     * 新用户注册
     **/
    owner.reg = function (regInfo, callback) {
        callback = callback || $.noop;
        regInfo = regInfo || {};
        regInfo.account = regInfo.account || '';
        regInfo.password = regInfo.password || '';
        if (regInfo.account.length < 5) {
            return callback('用户名最短需要 5 个字符');
        }
        if (regInfo.password.length < 6) {
            return callback('密码最短需要 6 个字符');
        }
        if (!checkEmail(regInfo.email)) {
            return callback('邮箱地址不合法');
        }
        var users = JSON.parse(localStorage.getItem('$users') || '[]');
        users.push(regInfo);
        localStorage.setItem('$users', JSON.stringify(users));
        return callback();
    };

    /**
     * 获取当前状态
     **/
    owner.getState = function () {
        var stateText = localStorage.getItem('$state') || "{}";
        return JSON.parse(stateText);
    };

    /**
     * 获取当前URL
     *
     * @returns {string}
     */
    owner.getRootPath = function () {
        var strFullPath = window.document.location.href;
        var strPath = window.document.location.pathname;
        var pos = strFullPath.indexOf(strPath);
        var prePath = strFullPath.substring(0, pos);
        var postPath = strPath.substring(0, strPath.substr(1).indexOf('/') + 1);
        var result = (prePath + postPath);
        if (result.indexOf('Layout') > -1)
            result = result.substring(0, result.indexOf('Layout'));
        return result;
    }

    /**
     * 设置当前状态
     **/
    owner.setState = function (state) {
        state = state || {};
        localStorage.setItem('$state', JSON.stringify(state));
    };

    var checkEmail = function (email) {
        email = email || '';
        return (email.length > 3 && email.indexOf('@') > -1);
    };

    /**
     * 找回密码
     **/
    owner.forgetPassword = function (email, callback) {
        callback = callback || $.noop;
        if (!checkEmail(email)) {
            return callback('邮箱地址不合法');
        }
        return callback(null, '新的随机密码已经发送到您的邮箱，请查收邮件。');
    };

    /**
     * 获取应用本地配置
     **/
    owner.setSettings = function (settings) {
        settings = settings || {};
        localStorage.setItem('$settings', JSON.stringify(settings));
    }
    /*
     * 获取当前登录用户
     */
    owner.getUser = function () {
        //	var user = eval('(' + localStorage.getItem("$user") + ')');
        var user = localStorage.getItem('$AdminUserInfo') || "{}";
        return JSON.parse(user);
    }
    /**
     * 设置应用本地配置
     **/
    owner.getSettings = function () {
        var settingsText = localStorage.getItem('$settings') || "{}";
        return JSON.parse(settingsText);
    }

    // 获取url参数
    owner.getUrlParam = function (param) {
        var params = decodeURIComponent(location.search.substring(1));
        var strs = params.split('&');
        var theRequest = {};
        for (var i = 0; i < strs.length; i++)
            theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
        return theRequest[param];
    };
}(window.app = {}));